package com.masterstroke.template.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.masterstroke.template.common.constant.MessageConstant;
import com.masterstroke.template.common.exception.BaseException;
import com.masterstroke.template.common.utils.Encipher;
import com.masterstroke.template.pojo.domain.User;
import com.masterstroke.template.pojo.dto.UserLoginDTO;
import com.masterstroke.template.service.UserService;
import com.masterstroke.template.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;

/**
* @author 35925
* @description 针对表【user】的数据库操作Service实现
* @createDate 2024-12-15 16:07:47
*/
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
implements UserService{

    @Autowired
    private UserMapper userMapper;

    @Override
    public User getUserByName(String username) {
        QueryWrapper<User> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("user_name",username);
        List<User> users = userMapper.selectList(queryWrapper);
        if(users.size()==0){
            return null;
        }
        return users.get(0);
    }

    @Override
    public User login(UserLoginDTO userLoginDTO) {
        String username = userLoginDTO.getUsername();
        String password = userLoginDTO.getPassword();

        //1、根据用户名查询数据库中的数据
        QueryWrapper<User> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("user_name",username);
        List<User> user = userMapper.selectList(queryWrapper);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (user.isEmpty()) {
            //账号不存在
            throw new BaseException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        // 进行MD5加密处理
        log.info("password:{}", Encipher.getUUID(password));
        password = Encipher.getUUID(password);
        if (!password.equals(user.get(0).getUserPassword())) {
            //密码错误
            throw new BaseException(MessageConstant.PASSWORD_ERROR);
        }
        //3、返回实体对象
        return user.get(0);
    }
}
